package com.hatricks.is.common.exception;

import cn.hutool.core.collection.CollUtil;
import com.hatricks.is.common.dto.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 检查接口入参
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public <T> Response<T> bizExceptionHandler(HttpServletRequest req, BusinessException ex) {
        logger.error("发生业务异常,原因是:[{}]", ex.getMessage());
        return Response.fail("业务异常,异常信息为:[{}]", ex.getMessage());
    }

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public <T> Response<T> bizExceptionHandler(MethodArgumentNotValidException ex) {
        logger.error("参数校验失败,原因是:[{}]", ex.getMessage());
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String message = ex.getMessage();
        if (CollUtil.isNotEmpty(fieldErrors)) {
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                message = field + defaultMessage;
            }
        }
        return Response.fail("业务异常,异常信息为:[{}]", message);
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public <T> Response<T> exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("发生未知异常！原因是栈帧为:", e);
        return Response.fail("发生异常,异常信息为:[{}]", e.getMessage());
    }
}
